spa.shell = (function(){
  'use strict';
    //-------------------------BEGIN MODULE SCOPE VARIABLES ------------------ 
    var
       configMap = {
           anchor_schema_map : {
            chat : {
                opened : true,
                closed : true
            }   
           },
           main_html : String()
            + '<div class="spa-shell-head">'
                + '<div class="spa-shell-head-logo">'
                + '<h1>SPA</h1>'
                + '<p>javascript end to end</p>'
                + '</div>'
                + '<div class="spa-shell-head-acct"></div>'
            + '</div>'
            + '<div class="spa-shell-main">'
                + '<div class="spa-shell-main-nav"></div>'
                + '<div class="spa-shell-main-content"></div>'
            + '</div>'
            + '<div class="spa-shell-foot"></div>'
            + '<div class="spa-shell-modal"></div>',
           
           chat_extend_time : 1000,
           chat_retract_time : 300,
           chat_extend_height :450,
           chat_retract_height : 15,
           chat_extended_title : 'Click to retract',
           chat_retracted_title : 'Click to extend',
           
           resize_interval : 200
           
   },
        //将在整个模块共享的动态信息放在stateMap中
       stateMap = {
           $container : undefined,
           anchor_map : {},
           resize_idto : undefined
       },
        //将jQuery集合缓存在jqueryMap中
       jqueryMap = {      
       },
       copyAnchorMap, setJqueryMap, 
       changeAnchorPart, onHashchange, onResize,
        onTapAcct, onLogin, onLogout,
       setChatAnchor , initModule;
    
    //------------------------ END MODULE SCOPE VARIABLES ------------------ 
    //------------------------ BEGIN UTILITY METHODS ------------------ 
    //这里的函数不和页面直接交互
    copyAnchorMap = function(){
     //使用深拷贝复制stateMap.anchor_map对象放入空对象中返回。
     return $.extend(true, {}, stateMap.anchor_map);   
    };
    //------------------------ END UTILITY METHODS ------------------ 
    
    //------------------------ BEGIN DOM METHODS ------------------ 
    setJqueryMap = function(){
        var $container = stateMap.$container;
        jqueryMap = {
            $container : $container,
            $acct : $container.find('.spa-shell-head-acct'),
            $nav : $container.find('.spa-shell-main-nav')
        };
    };
    //唯一修改锚的地方，集中统一管理锚的逻辑
    changeAnchorPart = function(arg_map) {
        var
            anchor_map_revise = copyAnchorMap(),
            bool_return = true,
            key_name, key_name_dep;
        
        KEYVAL:
        for(key_name in arg_map){
            if(arg_map.hasOwnProperty(key_name)){
                if(key_name.indexOf('_') === 0){
                    continue KEYVAL;
                }
                
                anchor_map_revise[key_name] = arg_map[key_name];
                
                key_name_dep = '_' + key_name;
                if(arg_map[key_name_dep]){
                    anchor_map_revise[key_name_dep] = arg_map[key_name_dep];
                }
                else{
                    delete anchor_map_revise[key_name_dep];
                    delete anchor_map_revise['_s'+key_name_dep];
                }
            }
        }
        
        try {
            $.uriAnchor.setAnchor(anchor_map_revise);
        }
        catch (error){
            $.uriAnchor.setAnchor(stateMap.anchor_map, null, true);
            bool_return = false;
        }
        
        return bool_return;
    };
    
    //------------------------ END DOM METHODS ------------------ 
    
    //------------------------ BEGIN EVENT HANDLERS------------------ 
    //事件处理函数的保留区
    onHashchange = function (event) {
       var 
           _s_chat_previous, _s_chat_proposed, s_chat_proposed,
           anchor_map_proposed,
           is_ok = true,
           anchor_map_previous = copyAnchorMap();
        try{
            anchor_map_proposed = $.uriAnchor.makeAnchorMap();
        }
        catch (error){
            $.uriAnchor.setAnchor(anchor_map_previous, null, true);
            return false;
        }
        stateMap.anchor_map = anchor_map_proposed;
        
        _s_chat_previous = anchor_map_previous._s_chat;
        _s_chat_proposed = anchor_map_proposed._s_chat;
        if(!anchor_map_previous
        || _s_chat_previous !== _s_chat_proposed) {
            s_chat_proposed = anchor_map_proposed.chat;
            switch (s_chat_proposed){
                case 'opened' :
                    is_ok = spa.chat.setSliderPosition('opened');
                    break;
                case 'closed':
                    is_ok = spa.chat.setSliderPosition('closed');
                    break;
                default:
                    spa.chat.setSliderPosition('closed');
                    delete anchor_map_proposed.chat;
                    $.uriAnchor.setAnchor(anchor_map_proposed, null, true);
            }
        }
        
        if(!is_ok) {
            if(anchor_map_previous) {
                $.uriAnchor.setAnchor(anchor_map_previous, null, true);
                stateMap.anchor_map = anchor_map_previous;
            }else{
                delete anchor_map_proposed.chat;
                $.uriAnchor.setAnchor(anchor_map_proposed,null, true);
            }
        }
       return false; 
    };
    onResize = function(){
      if(stateMap.resize_idto) {
          return true;
      }
        spa.chat.handleResize();
        stateMap.resize_idto = setTimeout(
            function(){
               stateMap.resize_idto = undefined; 
            },
            configMap.resize_interval
        );
        return true;
    };

    onTapAcct = function() {
      var acct_text, user_name, user = spa.model.people.get_user();
      if( user.get_is_anon() ) {
        user_name = prompt( 'Please sing-in' );
        spa.model.people.login( user_name );
        jqueryMap.$acct.text('... processing ...');
      }else {
        spa.model.people.logout();
      }
      return false;
    };

    onLogin = function( event, login_user ) {
      jqueryMap.$acct.text( login_user.name );
    };

    onLogout = function( evnet, logout_user ) {
      jqueryMap.$acct.text('Please sign-in');
    };
    //------------------------ END EVENT HANDLERS------------------ 
    //------------------------ BEGIN CALLBACK------------------ 
    setChatAnchor = function (position_type) {
        return changeAnchorPart({
            chat : position_type
        });  
    };
    //------------------------ END CALLBACK------------------ 
    //------------------------ BEGIN PUBLIC METHODS ------------------ 
    initModule = function($container){
        //$container代表传入的容器控件,存入stateMap用于后续处理
       stateMap.$container = $container;
        //填充html文本,动态更新容器布局
        $container.html(configMap.main_html);
        //将jQuery组件缓存起来可以优化性能
        setJqueryMap();
        
       $.uriAnchor.configModule({
           schema_map : configMap.anchor_schema_map
       });
        spa.chat.configModule({
            set_chat_anchor : setChatAnchor,
            chat_model : spa.model.chat,
            people_model : spa.model.people
        });
        spa.chat.initModule(jqueryMap.$container);
        //为浏览器绑定hashchange事件，并且触发该事件。
       $(window)
           .bind('resize', onResize)
           .bind('hashchange', onHashchange)
           .trigger('hashchange');

      $.gevent.subscribe( $container, 'spa-login', onLogin);
      $.gevent.subscribe( $container, 'spa-logout', onLogout);

      jqueryMap.$acct.text( 'Please sign-in' ).bind('utap', onTapAcct);
    };
    //------------------------ END PUBLIC METHODS ------------------ 
    return {
        initModule: initModule
    };
        
}());
